﻿using System;
using System.Collections.Generic;
using System.CodeDom;
using BMC.ARSystem;

namespace Wicresoft.EKA.NRemedy.CodeGenerate
{
    public class GenerateProperty : GeneratePropertyBase
    {
        public override void Create(CodeTypeDeclaration classType, string propertyName, string propertyType, Limit limit, Dictionary<string, object> attributePropertyValues, GeneratePropertyDelegate propertyDelegate, IGeneratePropertyAttribute attributeGenerator)
        {
            if (classType == null) throw new ArgumentNullException("classType");
            if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
            if (string.IsNullOrEmpty(propertyType)) throw new ArgumentNullException("propertyType");
            //if (limit == null) throw new ArgumentNullException("limit");
            if (attributePropertyValues == null) throw new ArgumentNullException("attributePropertyValues");
            if (propertyDelegate == null) throw new ArgumentNullException("propertyDelegate");
            if (attributeGenerator == null) throw new ArgumentNullException("attributeGenerator");
            base.Create(classType, propertyName, propertyType, limit, attributePropertyValues, propertyDelegate, attributeGenerator);

            if (propertyDelegate(propertyName))
            {
                GenerateNameResolver gnr = new GenerateNameResolver();
                CodeMemberProperty _property = new CodeMemberProperty();
                _property.Name = propertyName;
                _property.Type = new CodeTypeReference(propertyType);
                _property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                string fieldName = gnr.DefaultFieldNameResolver(propertyName);
                _property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName)));
                _property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName), new CodePropertySetValueReferenceExpression()));
                _property.SetStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "OnPropertyChanged"), new CodeExpression[] { new CodePrimitiveExpression(propertyName) }));

                //add attribute
                if (attributePropertyValues["DatabaseID"].ToString() == "1")
                    attributeGenerator.Create(_property, typeof(AREntryKeyAttribute), null);

                attributeGenerator.Create(_property, typeof(ARFieldAttribute), attributePropertyValues);

                classType.Members.Add(_property);
            }
        }
    }
}
